package com.sskj.finance.ui.fragment;


import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextSwitcher;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.sskj.common.adapter.ItemClickSupport;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.finance.R;
import com.sskj.finance.R2;
import com.sskj.finance.bean.BalanceCqtfBean;
import com.sskj.finance.bean.FinanBannerBean;
import com.sskj.finance.bean.FinanBean;
import com.sskj.finance.presenter.FinanceFragmentPresenter;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.mvchelper.ModelRx2DataSource;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

@Route(path = RConfig.FINAN_MAIN)
public class FinanceFragment extends BaseFragment<FinanceFragmentPresenter> {
    @BindView(R2.id.ivSee)
    ImageView ivSee;
    @BindView(R2.id.llRecord)
    LinearLayout llRecord;
    @BindView(R2.id.tvMoney)
    TextView tvMoney;
    @BindView(R2.id.tvNotice)
    TextSwitcher tvNotice;
    @BindView(R2.id.llNotice)
    LinearLayout llNotice;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    private Disposable noticeDispo;
    private String balance;
    private boolean isSee;


    @Override
    protected int getLayoutId() {
        return R.layout.finance_fragment_main;
    }

    @Override
    public FinanceFragmentPresenter getPresenter() {
        return new FinanceFragmentPresenter();
    }

    @Override
    protected void initData() {
        mPresenter.finanBanner();
        mPresenter.getBalance();
    }

    @Override
    protected void initView() {
        tvNotice.setFactory(() -> {
            TextView textView = new TextView(getActivity());
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PT, 28);
            textView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            textView.setGravity(Gravity.CENTER_VERTICAL);
            textView.setSingleLine();
            textView.setEllipsize(TextUtils.TruncateAt.END);
            textView.setTextColor(ContextCompat.getColor(App.INSTANCE, R.color.finan_788));
            return textView;
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity())
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 1))
                .setRightPadding((int) RudenessScreenHelper.pt2px(App.INSTANCE, 30))
                .setLeftPadding((int) RudenessScreenHelper.pt2px(App.INSTANCE, 30))
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.finan_bdc))
        );
        SlimAdapter slimAdapter = SlimAdapter.create().register(R.layout.finan_recy_item_finan_main, new SlimInjector<FinanBean>() {
            @Override
            public void onInject(FinanBean data, IViewInjector injector, List payloads) {

                injector
                        .text(R.id.tvName, data.getName())
                        .text(R.id.tvTime, String.format(App.INSTANCE.getString(R.string.finan_financeFragment1_j), data.getStarttime(), data.getEndtime()))
                        .text(R.id.tvRate, data.getExpect_rate() + "%")
                        .text(R.id.tvDay, data.getDays() + App.INSTANCE.getString(R.string.finan_myOrderActivity6_j))
                        .text(R.id.tvDayTitle, data.getDays() + App.INSTANCE.getString(R.string.finan_myOrderActivity6_j))
                        .text(R.id.tvLimit, String.format(App.INSTANCE.getString(R.string.finan_financeInfoActivity4_j), data.getNum_min()));
            }
        }).attachTo(recyclerView).updateData(new ArrayList());
        ModelRx2DataSource<FinanBean> dataSource = new ModelRx2DataSource<>((ModelRx2DataSource.OnLoadSource<FinanBean>)
                page -> {
                    mPresenter.getBalance();
                    return mPresenter.finanList(page + "", "20");
                }, 20);
        MVCCoolHelper<List<FinanBean>> mvcHelper = new MVCCoolHelper<>(coolRefreshView);
        mvcHelper.setDataSource(dataSource);
        mvcHelper.setAdapter(slimAdapter);
        mvcHelper.refresh();
        ItemClickSupport.addTo(recyclerView)
                .setOnItemClickListener((recyclerView1, i, view) -> {
                    FinanBean dataItem = (FinanBean) slimAdapter.getDataItem(i);
                    ARouter.getInstance().build(RConfig.FINAN_INFO)
                            .withString(Constans.ID, dataItem.getId())
                            .withString(Constans.NAME, dataItem.getName())
                            .navigation();
                });
    }

    @Override
    protected void initEvent() {
        ClickUtil.click(llRecord, () -> {
            ARouter.getInstance().build(RConfig.FINAN_MY_ORDER).navigation();
        });
    }

    public void updateBanner(List<String> data) {
        if (tvNotice != null) {
            if (data.size() > 0) {
                DisposUtil.close(noticeDispo);
                noticeDispo = Flowable.interval(0, 5, TimeUnit.SECONDS)
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(i -> {
                            if (tvNotice != null) {
                                String text = data.get((int) (i % data.size()));
                                tvNotice.setText(text);

                            }
                        }, System.out::println);
            }
        }
    }

    @Override
    public void onDestroy() {
        DisposUtil.close(noticeDispo);
        super.onDestroy();
    }

    @Override
    public void onResume() {
        if (mPresenter != null) {
            mPresenter.getBalance();
        }
        super.onResume();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden&&mPresenter!=null){
            mPresenter.getBalance();
        }
    }

    public void updateBalance(BalanceCqtfBean data) {
        balance = data.getUsable();
        tvMoney.setText("CQTF："+data.getUsable());
        ClickUtil.click(100, ivSee, () -> {
            isSee = !isSee;
            tvMoney.setText(isSee ? balance : "****");
            ivSee.setImageResource(isSee ? R.mipmap.lib_icon_see : R.mipmap.lib_icon_unsee);
        });
    }
}
